package com.atguigu.eduorder.comtroller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.commentutils.MD5;
import com.atguigu.commentutils.R;
import com.atguigu.eduorder.service.PayLogService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/eduorder/paylog")
@CrossOrigin
@Api(description = "支付管理")
public class PayLogController {

    @Autowired
    private PayLogService payLogService;

    //生成微信支付二维码接口
    //参数是订单
    @GetMapping("createNative/{orderNo}")
    public R createNative(@PathVariable String orderNo){
        //返回信息包括二维码地址，以及其他需要的信息
        Map map = payLogService.createNative(orderNo);
        return R.ok().data("map:" ,map);
    }

    //第三方平台支付（趣盟收银台）
    @GetMapping("wechatPay")
    public R wechatPay(){
        //1.设置参数
        String payfor = "订单号：10021，需支付的金额：0.01";
        String amount ="0.01";
        JSONObject json = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = sdf.format(new Date());
        StringBuilder sign = new StringBuilder();
        sign.append("amount=").append(amount).append("&")
            .append("appid=").append("qm_zoqIB8Ujh9").append("&")
            .append("orderno=").append("10021").append("&")
            .append("payfor=").append(payfor).append("&")
            .append("timestamp=").append(time).append("&")
            .append("appsecret=").append("qms11834085BC68E62C954AB7E5B5D73A2027A00ECD97A8");
        String signMd5 = MD5.encrypt(String.valueOf(sign));
        //HTTP请求调用
        json.put("amount",amount);
        json.put("appid","qm_zoqIB8Ujh9");
        json.put("orderno","10021");
        json.put("payfor",payfor);
        json.put("timestamp",time);
        json.put("sign",signMd5);
        String url = "http://pay.shazure.com/payservice/createorder";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> entity = new HttpEntity<>(json,headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,entity,String.class);
        //跳转二维码界面 https://pay.shazure.com/payservice/board?partnerno=
        JSONObject response = (JSONObject) JSONObject.parse(responseEntity.getBody());
        if (response == null || response.getString("success").equals("false")){
            return R.error().data("success",response.getString("success"));
        }else {
           String partnerno = response.getJSONObject("data").getString("partnerno");
           String expirein = response.getJSONObject("data").getString("expirein");
            return R.ok().data("partnerno",partnerno).data("expirein",expirein);
        }
    }

    //支付宝支付（沙箱）
    @GetMapping("zfbPay")
    public R zfbPay(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String result = null;
        try {
            //返回的是from标签
            result = payLogService.zfbPay();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  我们只需要将返回的这个标签进行跳转就行了，二维码是跳转之后就出来的，不用考虑获取二维码
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();

        return R.ok();
    }

    @GetMapping("/success")
    @ResponseBody
    public String success(){
        return "交易成功！";
    }
}
